<template>
  <div class="profile-container">
    <!-- 顶部导航 -->
    <div class="profile-header">
      <div class="header-left">
        <el-button :icon="'ArrowLeft'" @click="goBack">返回</el-button>
        <h1>个人中心</h1>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleUserCommand">
          <el-avatar :src="userStore.userInfo?.avatar" :icon="'UserFilled'" size="large" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item disabled>{{ userStore.userInfo?.username }}</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 用户信息卡片 -->
    <div class="user-info-card">
      <el-avatar :src="profileData?.avatar" :icon="'UserFilled'" :size="80" />
      <div class="user-info">
        <h2>{{ profileData?.username }}</h2>
        <p>加入时间: {{ formatDate(profileData?.joinDate || 0) }}</p>
      </div>
      <div class="user-stats">
        <div class="stat-item">
          <div class="stat-value">{{ profileData?.totalSessions || 0 }}</div>
          <div class="stat-label">对话次数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ profileData?.totalMessages || 0 }}</div>
          <div class="stat-label">消息数量</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ profileData?.bookmarks?.length || 0 }}</div>
          <div class="stat-label">收藏数量</div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="profile-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <!-- 关注点词云 -->
        <el-card class="card-section" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">🏷️ 我的关注点</span>
              <el-tooltip content="根据您的提问生成的关键词" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="topic-cloud" ref="topicCloudRef" v-loading="loading">
            <div
              v-for="(word, index) in topicCloudWords"
              :key="word.text"
              class="topic-word"
              :style="{
                fontSize: `${word.fontSize}px`,
                color: word.color,
                left: `${word.position.x}px`,
                top: `${word.position.y}px`
              }"
            >
              {{ word.text }}
            </div>
            <el-empty v-if="!profileData?.topicCloud?.length" description="暂无关注点数据" :image-size="100" />
          </div>
        </el-card>

        <!-- 兴趣趋势图 -->
        <el-card class="card-section" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">📈 兴趣趋势</span>
              <el-tooltip content="不同健康主题的咨询频率变化" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="trend-chart" ref="trendChartRef" v-loading="loading">
            <el-empty v-if="!profileData?.interestTrend?.length" description="暂无趋势数据" :image-size="100" />
          </div>
        </el-card>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- Tab切换 -->
        <el-tabs v-model="activeTab" class="profile-tabs">
          <!-- 我的收藏 -->
          <el-tab-pane label="📚 我的收藏" name="bookmarks">
            <div class="bookmarks-section">
              <div class="bookmarks-header">
                <el-select v-model="selectedCategory" placeholder="全部分类" clearable @change="handleCategoryChange">
                  <el-option label="全部分类" value="" />
                  <el-option label="心血管健康" value="心血管健康" />
                  <el-option label="生活方式" value="生活方式" />
                  <el-option label="营养健康" value="营养健康" />
                  <el-option label="心理健康" value="心理健康" />
                </el-select>
              </div>

              <div class="bookmarks-list" v-loading="bookmarksLoading">
                <div
                  v-for="bookmark in filteredBookmarks"
                  :key="bookmark.id"
                  class="bookmark-card"
                >
                  <div class="bookmark-header">
                    <h3>{{ bookmark.title }}</h3>
                    <el-button
                      :icon="'Delete'"
                      type="danger"
                      text
                      @click="handleDeleteBookmark(bookmark.id)"
                    />
                  </div>
                  <p class="bookmark-content">{{ truncateText(bookmark.content, 150) }}</p>
                  <div class="bookmark-meta">
                    <el-tag size="small">{{ bookmark.category }}</el-tag>
                    <el-tag
                      v-for="tag in bookmark.tags"
                      :key="tag"
                      size="small"
                      type="info"
                    >
                      {{ tag }}
                    </el-tag>
                    <span class="bookmark-time">{{ formatRelativeTime(bookmark.createdAt) }}</span>
                  </div>
                </div>

                <el-empty
                  v-if="!filteredBookmarks.length"
                  description="暂无收藏"
                  :image-size="120"
                />
              </div>
            </div>
          </el-tab-pane>

          <!-- 历史对话 -->
          <el-tab-pane label="💬 历史对话" name="history">
            <div class="history-section" v-loading="historyLoading">
              <div
                v-for="session in sessions"
                :key="session.id"
                class="history-card"
                @click="goToSession(session.id)"
              >
                <div class="history-header">
                  <h3>{{ session.title }}</h3>
                  <el-tag size="small">
                    {{ session.messages?.length || 0 }} 条消息
                  </el-tag>
                </div>
                <p class="history-preview">{{ session.lastMessage || '暂无消息' }}</p>
                <div class="history-meta">
                  <span>{{ formatRelativeTime(session.updatedAt) }}</span>
                  <el-button
                    :icon="'Delete'"
                    type="danger"
                    text
                    size="small"
                    @click.stop="handleDeleteSession(session.id)"
                  />
                </div>
              </div>

              <el-empty
                v-if="!sessions.length"
                description="暂无历史对话"
                :image-size="120"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';
import { useUserStore } from '@/stores/user';
import { useSessionStore } from '@/stores/session';
import { getUserProfile } from '@/api/profile';
import { deleteSession as deleteSessionApi } from '@/api/chat';
import { formatDate, formatRelativeTime, truncateText } from '@/utils/format';
import type { UserProfile, Bookmark, TopicWord } from '@/types/profile';

const router = useRouter();
const userStore = useUserStore();
const sessionStore = useSessionStore();

const loading = ref(false);
const bookmarksLoading = ref(false);
const historyLoading = ref(false);
const activeTab = ref('bookmarks');
const selectedCategory = ref('');
const profileData = ref<UserProfile | null>(null);
const trendChartRef = ref<HTMLElement>();
const topicCloudRef = ref<HTMLElement>();
let chartInstance: echarts.EChartsType | null = null;

// 扩展TopicWord类型以包含位置和字体大小
interface TopicCloudWord extends TopicWord {
  fontSize: number;
  position: { x: number; y: number };
}

const topicCloudWords = ref<TopicCloudWord[]>([]);

const sessions = computed(() => sessionStore.sessions);

const filteredBookmarks = computed(() => {
  if (!profileData.value?.bookmarks) return [];
  if (!selectedCategory.value) return profileData.value.bookmarks;
  return profileData.value.bookmarks.filter((b: Bookmark) => b.category === selectedCategory.value);
});

// 返回
const goBack = () => {
  router.push('/chat');
};

// 用户操作
const handleUserCommand = (command: string) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      userStore.logout();
      sessionStore.clearSessions();
      router.push('/login');
    }).catch(() => {});
  }
};

// 分类变化
const handleCategoryChange = () => {
  // 分类已通过computed自动过滤
};

// 删除收藏
const handleDeleteBookmark = async (bookmarkId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这条收藏吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    if (profileData.value?.bookmarks) {
      profileData.value.bookmarks = profileData.value.bookmarks.filter((b: Bookmark) => b.id !== bookmarkId);
      ElMessage.success('删除成功');
    }
  } catch (error) {
    // 用户取消
  }
};

// 删除会话
const handleDeleteSession = async (sessionId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteSessionApi(sessionId);
    if (response.code === 200) {
      sessionStore.removeSession(sessionId);
      ElMessage.success('删除成功');
    }
  } catch (error) {
    // 用户取消或删除失败
  }
};

// 跳转到会话
const goToSession = (sessionId: string) => {
  router.push(`/chat/${sessionId}`);
};

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value || !profileData.value?.interestTrend) return;

  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(trendChartRef.value);

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['营养', '心理', '运动', '综合']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: profileData.value.interestTrend.map((d: any) => d.date.substring(5))
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '营养',
        type: 'line',
        smooth: true,
        data: profileData.value.interestTrend.map((d: any) => d.nutrition),
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '心理',
        type: 'line',
        smooth: true,
        data: profileData.value.interestTrend.map((d: any) => d.mental),
        itemStyle: { color: '#E6A23C' }
      },
      {
        name: '运动',
        type: 'line',
        smooth: true,
        data: profileData.value.interestTrend.map((d: any) => d.exercise),
        itemStyle: { color: '#F56C6C' }
      },
      {
        name: '综合',
        type: 'line',
        smooth: true,
        data: profileData.value.interestTrend.map((d: any) => d.general),
        itemStyle: { color: '#409EFF' }
      }
    ]
  };

  chartInstance.setOption(option);

  // 响应式
  const resizeObserver = new ResizeObserver(() => {
    chartInstance?.resize();
  });
  resizeObserver.observe(trendChartRef.value);
};

// 初始化词云布局
const initTopicCloud = () => {
  if (!topicCloudRef.value || !profileData.value?.topicCloud) return;

  const containerWidth = topicCloudRef.value.clientWidth - 100;
  const containerHeight = 250;
  const words = profileData.value.topicCloud;
  
  // 计算字体大小
  const maxValue = Math.max(...words.map((w: TopicWord) => w.value));
  const minValue = Math.min(...words.map((w: TopicWord) => w.value));
  const valueRange = maxValue - minValue || 1;
  
  // 随机布局算法
  const result: TopicCloudWord[] = [];
  const occupiedAreas: Array<{ x: number; y: number; width: number; height: number }> = [];
  
  // 按value从大到小排序
  const sortedWords = [...words].sort((a, b) => b.value - a.value);
  
  sortedWords.forEach(word => {
    // 计算字体大小 (16px - 44px)
    const ratio = (word.value - minValue) / valueRange;
    const fontSize = Math.floor(16 + ratio * 28);
    
    // 估算文字宽度 (简单估算,实际宽度会有偏差)
    const estimatedWidth = word.text.length * fontSize * 0.6;
    const estimatedHeight = fontSize * 1.5;
    
    let position = { x: 0, y: 0 };
    let attempts = 0;
    let overlapping = true;
    
    // 尝试找到不重叠的位置
    while (overlapping && attempts < 100) {
      position.x = Math.random() * (containerWidth - estimatedWidth);
      position.y = Math.random() * (containerHeight - estimatedHeight);
      
      // 检查是否与已有区域重叠
      overlapping = occupiedAreas.some(area => {
        const padding = 10; // 间距
        return !(
          position.x + estimatedWidth + padding < area.x ||
          position.x - padding > area.x + area.width ||
          position.y + estimatedHeight + padding < area.y ||
          position.y - padding > area.y + area.height
        );
      });
      
      attempts++;
    }
    
    // 如果找不到完全不重叠的位置,使用最后一次尝试的位置
    occupiedAreas.push({
      x: position.x,
      y: position.y,
      width: estimatedWidth,
      height: estimatedHeight
    });
    
    result.push({
      ...word,
      fontSize,
      position
    });
  });
  
  topicCloudWords.value = result;
};

// 加载用户档案
const loadUserProfile = async () => {
  loading.value = true;
  try {
    const response = await getUserProfile();
    if (response.code === 200) {
      profileData.value = response.data;
      await nextTick();
      initTrendChart();
      initTopicCloud();
    }
  } catch (error: any) {
    ElMessage.error('加载用户档案失败');
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  loadUserProfile();
});

// 监听tab切换
watch(activeTab, (newTab) => {
  if (newTab === 'history' && !sessions.value.length) {
    // 可以在这里加载历史对话
  }
});
</script>

<style scoped lang="scss">
.profile-container {
  height: 100vh;
  background: #f5f7fa;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.profile-header {
  height: 64px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    h1 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
    }
  }
}

.user-info-card {
  background: white;
  padding: 32px;
  margin: 24px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 24px;

  .user-info {
    flex: 1;

    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .user-stats {
    display: flex;
    gap: 48px;

    .stat-item {
      text-align: center;

      .stat-value {
        font-size: 32px;
        font-weight: bold;
        color: #409eff;
        line-height: 1;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

.profile-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  padding: 0 24px 24px;
}

.left-panel,
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.card-section {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .card-title {
      font-size: 16px;
      font-weight: 600;
    }
  }
}

.topic-cloud {
  min-height: 200px;
  position: relative;
  padding: 20px;

  .topic-word {
    position: absolute;
    cursor: default;
    transition: all 0.3s;
    font-weight: 500;
    white-space: nowrap;

    &:hover {
      transform: scale(1.2);
      z-index: 10;
    }
  }
}

.trend-chart {
  height: 300px;
}

.profile-tabs {
  :deep(.el-tabs__content) {
    padding-top: 20px;
  }
}

.bookmarks-section {
  .bookmarks-header {
    margin-bottom: 16px;
  }

  .bookmarks-list {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .bookmark-card {
      padding: 20px;
      background: white;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      }

      .bookmark-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
        }
      }

      .bookmark-content {
        color: #606266;
        line-height: 1.6;
        margin-bottom: 12px;
      }

      .bookmark-meta {
        display: flex;
        gap: 8px;
        align-items: center;
        flex-wrap: wrap;

        .bookmark-time {
          margin-left: auto;
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

.history-section {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .history-card {
    padding: 20px;
    background: white;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      border-color: #409eff;
    }

    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .history-preview {
      color: #909399;
      font-size: 14px;
      margin-bottom: 12px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .history-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      color: #909399;
    }
  }
}

@media (max-width: 1200px) {
  .profile-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .user-info-card {
    flex-direction: column;
    text-align: center;

    .user-stats {
      width: 100%;
      justify-content: space-around;
    }
  }
}
</style>